#include <stdio.h>
#include <stdlib.h>

typedef struct Graph{
    char *vexs;
    int **arcs;
    int vexNum;
    int arcNum;
} Graph;

#define MAXSIZE 5 //数组长度

typedef struct Queue{
    int front;
    int rear;
    int data[MAXSIZE];
} Queue;

Queue* initQueue() 
{
    Queue *Q = (Queue *)malloc(sizeof(Queue));
    Q->front = Q->rear = 0;
    return Q;
}

int isFull(Queue *Q) 
{
    if ((Q->rear+1)%MAXSIZE == Q->front) return 1;
    return 0;
}

int isEmpty(Queue *Q) 
{
    if (Q->front == Q->rear) return 1;
    return 0;
}

int enQueue(Queue *Q, int data) 
{
    if (isFull(Q)) return 0;
    Q->data[Q->rear] = data;
    Q->rear = (Q->rear+1)%MAXSIZE;
    return 1;
}

int deQueue(Queue *Q) 
{
    if (isEmpty(Q)) return -1;
    int ret = Q->data[Q->front];
    //Q->front++;  
    Q->front = (Q->front + 1) % MAXSIZE;  
    return ret;
}

Graph *initGraph(int vexNum) //顶点数
{
    Graph *G = (Graph *)malloc(sizeof(Graph));
    G->arcs = (int **)malloc(sizeof(int *) * vexNum);
    G->vexs = (char *)malloc(sizeof(char) * vexNum);
    for (int i = 0; i < vexNum; i++) {
        G->arcs[i] = (int *)malloc(sizeof(int) * vexNum);
    }
    G->arcNum = 0;
    G->vexNum = vexNum;
    return G;
}

void creatGraph(Graph *G, char *vexs, int *arcs)
{
    for (int i = 0; i < G->vexNum; i++) {
        G->vexs[i] = vexs[i];
        for (int j = 0; j < G->vexNum; j++) { //注意此时只是普通的二级指针
            G->arcs[i][j] = *(arcs + i * G->vexNum + j);
            if (G->arcs[i][j] != 0) {
                G->arcNum++;
            }
        }
    }
    G->arcNum /= 2;
}

void DFS(Graph *G, int *visited, int index) //索引第一个节点开始
{
    printf("%c ", G->vexs[index]);//访问
    visited[index] = 1;
    for (int i = 0; i < G->vexNum; i++) {
        if (G->arcs[index][i] == 1 && !visited[i]) {//遍历 + 递归
            DFS(G, visited, i);
        }
    }
}

void BFS(Graph *G, int *visited, int index)
{
    printf("%c ", G->vexs[index]);
    visited[index] = 1;
    Queue *Q = initQueue();
    enQueue(Q, index);
    while (!isEmpty(Q)) {
        int tmp = deQueue(Q);
        for (int i = 0; i < G->vexNum; i++) {
            if (G->arcs[tmp][i] == 1 && !visited[i]) {
                printf("%c ", G->vexs[i]);
                visited[i] = 1;
                enQueue(Q, i);
            }
        }
    }
}

int main(void)
{
    int vexNum = 5;
    int arcs[5][5] = {
        0, 1, 1, 1, 0,
        1, 0, 1, 1, 1,
        1, 1, 0, 0, 0,
        1, 1, 0, 0, 1, 
        0, 1, 0, 1, 0,
    };
    Graph *G = initGraph(5);
    creatGraph(G, "ABCDE", (int *)arcs);
    int *visited = (int *)malloc(sizeof(int) * G->vexNum);
        for (int i = 0; i < vexNum; i++) {
            visited[i] = 0;
        }
    BFS(G, visited, 0);
    //DFS(G, visited, 0);
    return 0;
}